<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['jewelry:review:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jewelry:review:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jewelry:review:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['jewelry:review:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reviewList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评论ID" align="center" prop="id" />
      <el-table-column label="用户ID" align="center" prop="nickname" />
      <el-table-column label="产品ID" align="center" prop="productName" />
      <el-table-column label="首图" align="center" prop="mainImage" width="80">
        <template #default="scope">
          <image-preview :src="scope.row.mainImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="评分" align="center" prop="rating" />
      <el-table-column label="评论内容" align="center" prop="content" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['jewelry:review:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['jewelry:review:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评论管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="reviewRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户">
            <el-option 
              v-for="user in userList" 
              :key="user.id" 
              :label="user.nickname" 
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品ID" prop="productId">
          <div class="product-select">
            <el-button
              type="primary"
              plain
              @click="openProductDialog"
              :disabled="!userList.length"
            >选择产品</el-button>
            <span v-if="form.productId">{{ selectedProductName }}</span>
          </div>
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-input v-model="form.rating" placeholder="请输入评分" />
        </el-form-item>
        <el-form-item label="评论内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker clearable
            v-model="form.createTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>

      
    </el-dialog>

    <!-- 选择产品时弹窗-->
    <el-dialog :title="'选择产品'" v-model="productDialogVisible" width="800px" append-to-body>
      <!-- <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="productQueryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="searchProducts"
        />
        </el-form-item> -->
        <!-- <el-form-item>
          <el-button type="primary" icon="Search" @click="searchProducts">搜索</el-button>
          <el-button icon="Refresh" @click="resetProductSearch">重置</el-button>
        </el-form-item> -->
        <el-table v-loading="productLoading" :data="productList" @selection-change="handleProductChange" row-key="id">
          <el-table-column type="selection" width="55" align="center" :selectable="onlySingleSelect"/>
          <el-table-column label="产品名称" align="center" prop="name" />
        </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmProductSelection">确 定</el-button>
        </div>
      </template>
      <pagination
        v-show="productTotal>0"
        :total="productTotal"
        v-model:page="productQueryParams.pageNum"
        v-model:limit="productQueryParams.pageSize"
        @pagination="getProductList"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Review">
import { listReview, getReview, delReview, addReview, updateReview } from "@/api/jewelry/review";
import { listUser } from "@/api/jewelry/user.js"
import { listProduct } from "@/api/jewelry/product.js"

const { proxy } = getCurrentInstance();

const reviewList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const userList = ref([]);// 添加用户列表的变量
const productList = ref([]);// 添加产品列表的变量

// 新增产品选择相关响应式数据
const productDialogVisible = ref(false);
const productLoading = ref(false);
const productTotal = ref(0);
const selectedProduct = ref(null);
const selectedProductName = ref('');
const productSelection = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    productId: null,
    nickname: null,
    productName: null
  },
  productQueryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: null
  },
  rules: {
    userId: [
      { required: true, message: "请选择用户", trigger: "change" }
    ],
    productId: [
      { required: true, message: "请选择产品", trigger: "change" }
    ]
  }
});

//再从data解构（顺序：先定义data再解构）
const { queryParams, form, rules, productQueryParams } = toRefs(data);


/** 查询评论管理列表 */
function getList() {
  loading.value = true;
  listReview(queryParams.value).then(response => {
    reviewList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    productId: null,
    rating: null,
    content: null,
    createTime: null
  };
  proxy.resetForm("reviewRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加评论管理";
  getUserList();
  getProductList();
}

/** 修改按钮操作 */
async function handleUpdate(row) { // 1. 加async，允许内部用await
  reset();
  const _id = row.id || ids.value;
  
  try {
    const response = await getReview(_id);
    form.value = response.data; 
    open.value = true;
    title.value = "修改评论管理";
    
    // 加载用户列表和产品列表
    getUserList();
    await getProductList();
    
    if (form.value.productId) {
      selectedProductName.value = `产品ID: ${form.value.productId}`;
      const target = productList.value.find(p => p.id === form.value.productId);
      if (target) {
        selectedProductName.value = target.name; 
        selectedProduct.value = target;
      }
    }
  } catch (err) {
    console.error("修改评论加载失败：", err);
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["reviewRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateReview(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addReview(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除评论管理编号为"' + _ids + '"的数据项？').then(function() {
    return delReview(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('jewelry/review/export', {
    ...queryParams.value
  }, `review_${new Date().getTime()}.xlsx`)
}

/** 获取用户列表方法 */
function getUserList () {
  listUser().then(response => {
    userList.value = response.rows;
  })
}

/** 打开产品选择弹窗 */
function openProductDialog() {
  productDialogVisible.value = true;
  // 重置选择状态
  productSelection.value = [];
  selectedProduct.value = null;
  // 加载产品列表
  getProductList();
}

/** 搜索产品 */
function searchProducts() {
  productQueryParams.value.pageNum = 1;
  getProductList();
}

/** 重置产品搜索 */
function resetProductSearch() {
  productQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    productName: null
  };
  searchProducts();
}

/** 处理产品选择 */
function handleProductChange(selection) {
  productSelection.value = selection;
}

/** 限制只能单选 */
function onlySingleSelect() {
  return productSelection.value.length < 1;
}

/** 确认选择产品 */
function confirmProductSelection() {
  if (productSelection.value.length === 1) {
    selectedProduct.value = productSelection.value[0];
    form.value.productId = selectedProduct.value.id;
    selectedProductName.value = selectedProduct.value.productName;
    productDialogVisible.value = false;
  } else {
    proxy.$modal.msgWarning("请选择一个产品");
  }
}

/** 修改获取产品列表方法 */
function getProductList() {
  productLoading.value = true;
  listProduct(productQueryParams.value).then(response => {
    console.log("后端返回的产品列表：", productList.value);
    productList.value = response.rows;
    productTotal.value = response.total;
    productLoading.value = false;
  });
}
getUserList();
getProductList();
getList();
</script>
